package com.heima.datasync.service.impl;

import com.google.common.collect.Lists;
import com.heima.common.search.EsDataIndexConstants;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private EsService<SearchArticleVO> esService;

    @Override
    public ResponseResult dataInit() {
        // 判断索引库是否存在
        boolean exist = esService.existIndex(EsDataIndexConstants.ARTICLE_INDEX_NAME);
        if (exist) {
            esService.deleteIndex(EsDataIndexConstants.ARTICLE_INDEX_NAME);
        }
        esService.createIndex(EsDataIndexConstants.ARTICLE_INDEX_MAPPING, EsDataIndexConstants.ARTICLE_INDEX_NAME);
        // 批量导入数据:
        List<ApArticle> apArticles = apArticleMapper.findAllArticles();
        if (apArticles == null || apArticles.size() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "数据库文章信息不存在");
        }
        //查询数据过多,将集合数据分组
        List<List<ApArticle>> partition = Lists.partition(apArticles, 2000);
        for (List<ApArticle> articles : partition) {
            // 遍历页码批量插入到索引库
            List<SearchArticleVO> list = new ArrayList<>();
            for (ApArticle article : articles) {
                // 封装数据
                SearchArticleVO articleVo = new SearchArticleVO();
                BeanUtils.copyProperties(article, articleVo);
                list.add(articleVo);
            }
            esService.saveBatch(list, EsDataIndexConstants.ARTICLE_INDEX_NAME);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}